// pages/manydays/manydays.js
const app = getApp()
const $req = require('../../utils/req.js') //接口封装文件
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dateMask:true,
    selectTimes: new Date().toISOString().substring(0, 10),
    endTimes: new Date().toISOString().substring(0, 10),
    marquee:{
      type:Boolean,
    },
    scheduleLegend: [{
      name: '可预订',
      color: '#D1D1D1',
    }, {
      name: '不可预订',
      color: '#777575'
    }, {
      name: '已预订',
      color: '#EA5826',
    }, {
      name: '已选中',
      color: '#FDB644',
    }],
    goodsList: [],
    goodsListTotalPrice: '0.00',
    disAmount: '0',
    date:new Date().toISOString().substring(0, 10),
    selectDays:null,
    datalist:[],
    timelist:[],
    RoomID:null,
    timeInterval: [0,0, 0],//选中日期和选中间距
    roomInfo:[],
    oklist:[],//多日选择 选择详情
    domoney:0,
    totalPrice:0,
    timelists:[],
    Descr:null,
  },
// 获取会议室可用时间段  传参数 会议室id和时间
getRoomTimesInfo(RoomID, Mdate) {
  let _this = this
  let data = {
    RoomID: RoomID,
    Mdate: Mdate,
  }
  $req.getRoomTimesInfo(data).then(res => {
    let result = res.DATA
    result.forEach((item, index) => {
      item.timePoint = item.FromTo.split("-")[0]
      item.checkFlag=false
    });
    _this.setData({
      roomTimes: result,
    })
  })
},

 getDate(datestr) {
  var temp = datestr.split("-");
  var date = new Date(temp[0], temp[1] - 1, temp[2]);
  return date;
},
//获得2天时间的间隔的列表
gettimelist(start,end){
  let that = this
  let dateList = []; 
  var start_time = new Date(start.replace(/-/g, "/"));
  var end_time = new Date(end.replace(/-/g, "/"));
  var days = end_time.getTime() - start_time.getTime();
  var day = parseInt(days / (1000 * 60 * 60 * 24));//间隔天数
  var datalist  = [];  
  let RoomID = that.data.RoomID
  for(var i=0;i<=day;i++){
    datalist.push(that.format(start_time.getTime()+i*(1000 * 60 * 60 * 24)));
  }
  that.setData({
    datalist:datalist,
  })
  let timelist = []
  datalist.forEach((elem, index) => {
  let data = {
    RoomID: RoomID,
    Mdate: elem,
  }
  $req.getRoomTimesInfo(data).then(res => {
    let result = res.DATA
    result.forEach((item, index) => {
      item.timePoint = item.FromTo.split("-")[0]
      item.checkFlag=false
    });
      timelist.push({
          daytime:elem,
          dayindex:index,
          times: result
        })
        that.setData({
          timelist:timelist
        })
  })
});
},
add0(m){return m<10?'0'+m:m },
format(shijianchuo)
{
  let that = this
//shijianchuo是整数，否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+'-'+that.add0(m)+'-'+that.add0(d);
},

//获得商品列表
getGoodsList(RoomID) {
  let _this = this
  let data = {
    RoomID: RoomID,
  }
  $req.getGoodsList(data).then(res => {
    let result = res.DATA
    result.forEach((item, index) => {
      item.num = 0
      item.Price = item.Price.toFixed(2)
      item.totalPrice = (item.Price * item.num).toFixed(2)
    })
    _this.setData({
      goodsList: res.DATA
    })
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   let that = this
   let date = new Date().toISOString().substring(0, 10)
   let userInfo = wx.getStorageSync('userInfo')
   let token = wx.getStorageSync('token')
   that.setData({
    RoomID:options.id
   })
  //  that.getRoomTimesInfo(options.id, date)
   that.getGoodsList(options.id)//获取初始化的商品
   let starttime =  that.data.selectTimes
   let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)
   //获取当前会议室的详细信息
   that.getRoomInfo(options.id)
   wx.request({
    url: 'https://www.yulonging.com/dwweb/wxapi.ashx?cmd=saveorder',
    data: {
      cmd: 'GetRoomDiscount',
      token: token,
      RoomID: options.id
    },
    method: "get",
    header: {
      'content-type': 'application/json' // 默认值
    },
    success (res) {
      that.setData({
        disAmount:res.data.DATA.Discount
      })
    }
  })
  },
  




  //会议室详情
  getRoomInfo(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID
    }
    $req.getRoomInfo(data).then(res => {
      console.log(res.DATA)
      _this.setData({
        roomInfo: res.DATA,
        // disAmount:res.DATA.disAmount
      })
    })
  },


  //返回上一页
  navigateBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**日期全选**/
  checkall(e){
    console.log(2222);
    console.log(e);
  },
 //打开时间选择器
 openDateMask(e){
  let _this = this
  _this.setData({
    dateMask:false,
    marquee:true
  })
},
endDateMask(e){
  let _this = this
  _this.setData({
    dateMask:false,
    marquee:false
  })
},
//关闭时间选择器
onSearchInputEvent(e){
  let that = this;
  let value = e.detail.dateMask;
  console.log(value);
    that.setData({
      dateMask:value
    })
   
},


onSearchEvent(e){
  let that = this;
  let select = e.detail.selectDays;
  let value = e.detail.clreashuju.dateMask; 
  let arrendTimes=that.data.endTimes;
  if(arrendTimes.length==0){
    that.setData({
      selectTimes:select,
      dateMask:value
    })
  }else{
    if(select <= arrendTimes){
      that.setData({
        selectTimes:select,
        dateMask:value
      })
    }else{
      that.setData({
        selectTimes:arrendTimes,
        endTimes:select,
        dateMask:value
      })
    }
  }
  let starttime =  that.data.selectTimes
  let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)

},
onEndEvent(e){
  let that = this;
  let select = e.detail.selectDays;
  let value = e.detail.clreashuju.dateMask; 
  let arrselectT=that.data.selectTimes;
  if(select > arrselectT){
    that.setData({
      endTimes:select,
      dateMask:value
    })
  }else{
    that.setData({
      endTimes:arrselectT,
      selectTimes:select,
      dateMask:value
    })
  }
  let starttime =  that.data.selectTimes
  let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)
},
 // 计算总金额
 totalPrice() {
  let _this = this
  let roomTiemsCopy = Object.create(_this.data.roomTimes)
  let totalPrice = 0
  roomTiemsCopy.forEach((item, index) => {
    if (item.checkFlag) {
      totalPrice += item.Price
    }
  })
  _this.setData({
    totalPrice: (totalPrice).toFixed(2),
    disAmount: (totalPrice*_this.data.dis).toFixed(2)*1,
  })
},

changeGoodsNum(e) {
  let _this = this
  let data = e.currentTarget.dataset
  let goodsList = _this.data.goodsList
  let goods = goodsList[data.index]
  switch (data.type) {
    case "+":
      goods.num += 1
      break
    case "-":
      goods.num -= 1
      break
  }
  if (goods.num < 0) {
    goods.num = 0
  }
  goods.totalPrice = (goods.num * goods.Price).toFixed(2)
  _this.goodsListTotalPrice()
  _this.finsTotalprice()
  _this.setData({
    goodsList: goodsList,
  })
  console.log(goodsList)
},

finsTotalprice() {
  let _this = this
  _this.setData({
    finsTotalprice: (parseFloat(_this.data.disAmount) + parseFloat(_this.data.goodsListTotalPrice)).toFixed(2),
  })
},

goodsListTotalPrice() {
  let _this = this
  let goodsListTotalPrice = 0
  let goodsList = _this.data.goodsList
  goodsList.forEach((item, index) => {
    goodsListTotalPrice += parseFloat(item.totalPrice)
  })
  _this.setData({
    goodsListTotalPrice: goodsListTotalPrice.toFixed(2)
  })
},


touchTimesTables(e){
  let that = this
  let roomInfo = that.data.roomInfo
  let catindex = e.currentTarget.dataset.index //用户点击的时间索引
  let list = e.currentTarget.dataset.list //用户点击的时间索引
  let times = e.currentTarget.dataset.times //用户点击的时间索引
  let timeInterval = that.data.timeInterval//选中日期和选中长度
  let typeValue = roomInfo.SortNm == "大型会议室" ? 7 : 3 //长度 大型会议室8个 小的4个选中
  let oklist = that.data.oklist
  //获取全部数据
  let timelist = that.data.timelist
  //获取30天数据
  let daytimelist = timelist[list].times
  //获取点击时间段数据
  let timeinfo = daytimelist[catindex]
  //判断是不是取消点击
  if(timeinfo.IsOrder==true){
    wx.showToast({
      title:'当日时间已被选择',
      icon: 'error',
      duration: 2000
    })
  }else{
    //可以选择
    if ((catindex + typeValue) > daytimelist.length - 1) {
      // 判断点击点位是否超过可选  如果是第一次点击提示  第二次点击选中
      if(timeInterval[0]==0){
        wx.showToast({
          title:'不足最低订购时间',
          icon: 'error',
          duration: 2000
        })
      }else{
      //判断是不是取消 如果不是取消就是新增  
        if(catindex<= timeInterval[2] && catindex>=timeInterval[1]){
          timeInterval[0] = 0
        }else{
          if(catindex<timeInterval[1]){
            timeInterval[1] =  catindex
            timeInterval[2] =  timeInterval[2] 
          }else if(catindex>timeInterval[2]){
            timeInterval[1] =  timeInterval[1]
            timeInterval[2] =  catindex
          }
        }
          //时间充足可以进行预定
        daytimelist.forEach((item, index) => {
          if(timeInterval[0]==0){
            if (index >= timeInterval[1] && index <=timeInterval[2] ) {
              item.checkFlag = false
            }
          }else{
            if (index >= timeInterval[1] && index <=timeInterval[2] ) {
                item.checkFlag = true
               
            }
          }          
        })
        oklist[list] = {
            list:list,
            index:timeInterval
        }
        timelist[list].times = daytimelist
        that.setData({
          oklist:oklist,
          timelist:timelist,
          timeInterval:timeInterval
        })
      }
    }else{
        //判断是不是同一日二次选中
        if(times==timeInterval[0]){
          timeInterval[0] = times
          if(catindex<timeInterval[1] || catindex>timeInterval[2]){
              //详细判断是点击大还是小
            if(catindex<timeInterval[1]){
              timeInterval[1] =  catindex
              timeInterval[2] =  timeInterval[2] 
      
            }else if(catindex>timeInterval[2]){
              timeInterval[1] =  timeInterval[1]
              timeInterval[2] =  catindex
         
            }
          }else{
                timeInterval[0] =  0
                if(catindex<timeInterval[1]){
                  timeInterval[1] =  catindex
                  timeInterval[2] =  timeInterval[2] 
                }else if(catindex>timeInterval[2]){
                  timeInterval[1] =  timeInterval[1]
                  timeInterval[2] =  catindex
                }
          }
        }else{
          //不是同一日
          timeInterval[0] = times
          timeInterval[1] =  catindex
          timeInterval[2] =  catindex+ typeValue
        }
        //时间充足可以进行预定
        daytimelist.forEach((item, index) => {
          if(timeInterval[0]==0){
            if (index >= timeInterval[1] && index <=timeInterval[2] ) {
              item.checkFlag = false
            }
          }else{
            if (index >= timeInterval[1] && index <=timeInterval[2] ) {
                  item.checkFlag = true
            }
          }          
        })
        //数据详情记录
        oklist[list] = {
          list:list,
          index:timeInterval
        }
        timelist[list].times = daytimelist
        that.setData({
          oklist:oklist,
          timelist:timelist,
          timeInterval:timeInterval
        })
    }
  }
  that.getmoneylist()
},
//计算金额加上折扣
getmoneylist(e){
  let that = this
  let timelist = that.data.timelist
  //根据预定的选中进行金额计算
  let oklist = that.data.oklist
  let listinfo = []
  oklist.forEach((item, index) => {
      listinfo[index] = timelist[index].times
  })
  let nolist = []
  listinfo.forEach((item, index) => {
    item.forEach((itmes,indexs)=>{
      nolist.push(itmes)
    })
  })
  let totalPrice = 0
  nolist.forEach((item,index)=>{
    if (item.checkFlag) {
      totalPrice += item.Price*1
    }
  })
  that.setData({
    totalPrice: (totalPrice).toFixed(2),
    domoney: (totalPrice*that.data.disAmount).toFixed(2)*1,
  })
},
getseiz(e){
console.log(e)
  let that = this
  that.setData({
    Descr:e.detail.value
  })


},
subok(e){
  //提交表单
  let that = this
  let Descr = that.data.Descr
  let goodsList = this.data.goodsList
  let oklist = that.data.oklist
  let timelist = that.data.timelist
  



}
  


})